package dongze.com.ckdj.adapter;

import android.databinding.DataBindingUtil;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import dongze.com.ckdj.R;
import dongze.com.ckdj.data.IRecordRequestBuilder;
import dongze.com.ckdj.data.entity.request.RecordOption;
import dongze.com.ckdj.data.entity.request.RecordRequestBody;
import dongze.com.ckdj.databinding.VehicleInformationListItemBinding;
import dongze.com.ckdj.databinding.model.InformationItemTextModel;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

/**
 * Created by fanqwz on 2017/7/21.
 */

public class VehicleInformationAdapter extends BaseAdapter implements IRecordRequestBuilder {
    ListItem[] listItems;

    public void setListItems(ListItem[] listItems) {
        this.listItems = listItems;
    }

    @Override
    public int getCount() {
        return listItems == null ? 0 : listItems.length;
    }

    @Override
    public Object getItem(int position) {
        return listItems == null ? null : listItems[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            VehicleInformationListItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.vehicle_information_list_item, parent, false);
            convertView = binding.getRoot();
            convertView.setTag(binding);
        }

        VehicleInformationListItemBinding binding = (VehicleInformationListItemBinding) convertView.getTag();
        InformationItemTextModel model = new InformationItemTextModel();
        model.setKey(listItems[position].getKey());
        model.setValue(listItems[position].getValue());
        binding.setVehicleInformationItemText(model);
        return convertView;
    }

    public Observable<RecordRequestBody> build(final RecordRequestBody body) {
        return Observable.create(new ObservableOnSubscribe<RecordRequestBody>() {
            @Override
            public void subscribe(ObservableEmitter<RecordRequestBody> e) throws Exception {
                for (ListItem item : listItems) {
                    RecordOption r = new RecordOption();
                    r.setProgram_id("0");
                    r.setProgram_name(item.getKey());
                    r.setProgram_value(item.getValue());
                    body.getOptions().add(r);
                }

                e.onNext(body);
                e.onComplete();
            }
        });
    }
}
